import * as vscode from 'vscode';

// For VSCode extensions, we need to create a WebView to use browser APIs like speechSynthesis
let webViewPanel: vscode.WebviewPanel | undefined;

export async function speakText(text: string): Promise<void> {
    // Get configuration settings
    const config = vscode.workspace.getConfiguration('codeReader');
    const ttsEnabled = config.get<boolean>('ttsEnabled', true);
    
    if (!ttsEnabled) {
        // If TTS is disabled, just show the text in an info message
        vscode.window.showInformationMessage(`Code Analysis: ${text}`);
        return Promise.resolve();
    }
    
    // In VSCode extensions, we need to use a webview to access speechSynthesis
    const extensionUri = (global as any).context ? (global as any).context.extensionUri : undefined;
    
    if (!extensionUri) {
        // If we don't have extension context, just show the text in an info message
        vscode.window.showInformationMessage(`Code Analysis: ${text}`);
        return Promise.resolve();
    }
    
    // Create or show the webview
    createOrShowWebView();
    
    // Send message to webview to speak the text
    if (webViewPanel) {
        webViewPanel.webview.postMessage({
            command: 'speak',
            text: text
        });
    }
}

function createOrShowWebView() {
    if (webViewPanel) {
        webViewPanel.reveal(vscode.ViewColumn.One);
    } else {
        webViewPanel = vscode.window.createWebviewPanel(
            'ttsWebView',
            'Text-to-Speech',
            vscode.ViewColumn.One,
            {
                enableScripts: true,
                retainContextWhenHidden: true
            }
        );
        
        webViewPanel.webview.html = getWebviewContent();
        
        // Handle messages from the webview
        webViewPanel.webview.onDidReceiveMessage(
            message => {
                switch (message.command) {
                    case 'speakCompleted':
                        console.log('TTS completed for:', message.text);
                        break;
                }
            },
            undefined
        );
        
        // Clean up when panel is closed
        webViewPanel.onDidDispose(() => {
            webViewPanel = undefined;
        }, null, (global as any).context?.subscriptions || []);
    }
}

function getWebviewContent(): string {
    // Get configuration settings
    const config = vscode.workspace.getConfiguration('codeReader');
    const defaultRate = config.get<number>('ttsRate', 1.0);
    const defaultPitch = config.get<number>('ttsPitch', 1.0);
    const defaultVolume = config.get<number>('ttsVolume', 1.0);
    
    return `
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Text-to-Speech</title>
            <style>
                body {
                    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                    padding: 20px;
                    background-color: #f5f5f5;
                }
                .container {
                    max-width: 800px;
                    margin: 0 auto;
                    background-color: white;
                    padding: 20px;
                    border-radius: 8px;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                }
                h1 {
                    color: #333;
                    text-align: center;
                }
                .status {
                    text-align: center;
                    margin: 20px 0;
                    padding: 10px;
                    background-color: #e7f3fe;
                    border-radius: 4px;
                }
                .input-group {
                    margin: 15px 0;
                }
                label {
                    display: block;
                    margin-bottom: 5px;
                    font-weight: bold;
                }
                input, select {
                    width: 100%;
                    padding: 8px;
                    border: 1px solid #ddd;
                    border-radius: 4px;
                    box-sizing: border-box;
                }
                button {
                    background-color: #007acc;
                    color: white;
                    border: none;
                    padding: 10px 20px;
                    border-radius: 4px;
                    cursor: pointer;
                    margin: 5px;
                }
                button:hover {
                    background-color: #005a9e;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <h1>Code Reader - Text-to-Speech</h1>
                <div class="status" id="status">Ready to speak code analysis</div>
                
                <div class="input-group">
                    <label for="text">Text to speak:</label>
                    <input type="text" id="text" placeholder="Text will be spoken here...">
                </div>
                
                <div class="input-group">
                    <label for="rate">Rate (0.1 - 10):</label>
                    <input type="number" id="rate" min="0.1" max="10" step="0.1" value="${defaultRate}">
                </div>
                
                <div class="input-group">
                    <label for="pitch">Pitch (0 - 2):</label>
                    <input type="number" id="pitch" min="0" max="2" step="0.1" value="${defaultPitch}">
                </div>
                
                <div class="input-group">
                    <label for="volume">Volume (0 - 1):</label>
                    <input type="number" id="volume" min="0" max="1" step="0.1" value="${defaultVolume}">
                </div>
                
                <button id="speakBtn">Speak Text</button>
                <button id="cancelBtn">Cancel Speech</button>
                
                <div id="voicesList"></div>
            </div>

            <script>
                (function() {
                    const vscode = acquireVsCodeApi();
                    let utterance = null;
                    
                    // Initialize speech synthesis
                    const statusElement = document.getElementById('status');
                    const textElement = document.getElementById('text');
                    const speakBtn = document.getElementById('speakBtn');
                    const cancelBtn = document.getElementById('cancelBtn');
                    const rateElement = document.getElementById('rate');
                    const pitchElement = document.getElementById('pitch');
                    const volumeElement = document.getElementById('volume');
                    
                    // Populate voices list
                    function populateVoices() {
                        const voicesList = document.getElementById('voicesList');
                        voicesList.innerHTML = '';
                        
                        const voices = speechSynthesis.getVoices();
                        const selectElement = document.createElement('select');
                        selectElement.id = 'voices';
                        
                        voices.forEach((voice, index) => {
                            const option = document.createElement('option');
                            option.value = index;
                            option.textContent = voice.name + ' (' + voice.lang + ')';
                            if (voice.default) {
                                option.textContent += ' -- DEFAULT';
                            }
                            selectElement.appendChild(option);
                        });
                        
                        const label = document.createElement('label');
                        label.textContent = 'Voice:';
                        label.htmlFor = 'voices';
                        
                        voicesList.appendChild(label);
                        voicesList.appendChild(selectElement);
                    }
                    
                    // Load voices initially and when voices change
                    populateVoices();
                    speechSynthesis.onvoiceschanged = populateVoices;
                    
                    // Function to speak text
                    function speakText(text) {
                        if (speechSynthesis.speaking) {
                            speechSynthesis.cancel();
                        }
                        
                        if (text !== '') {
                            const selectedVoice = speechSynthesis.getVoices()[document.getElementById('voices').value];
                            utterance = new SpeechSynthesisUtterance(text);
                            
                            utterance.voice = selectedVoice;
                            utterance.rate = parseFloat(rateElement.value);
                            utterance.pitch = parseFloat(pitchElement.value);
                            utterance.volume = parseFloat(volumeElement.value);
                            
                            utterance.onend = function(event) {
                                statusElement.textContent = 'Finished speaking: ' + text;
                                vscode.postMessage({
                                    command: 'speakCompleted',
                                    text: text
                                });
                            };
                            
                            utterance.onerror = function(event) {
                                statusElement.textContent = 'Error speaking: ' + event.error;
                            };
                            
                            statusElement.textContent = 'Speaking: ' + text;
                            speechSynthesis.speak(utterance);
                        } else {
                            statusElement.textContent = 'Please enter text to speak';
                        }
                    }
                    
                    // Event listeners
                    speakBtn.addEventListener('click', function() {
                        const text = textElement.value || statusElement.textContent;
                        if (text) {
                            speakText(text);
                        }
                    });
                    
                    cancelBtn.addEventListener('click', function() {
                        speechSynthesis.cancel();
                        statusElement.textContent = 'Speech cancelled';
                    });
                    
                    // Listen for messages from the extension
                    window.addEventListener('message', event => {
                        const message = event.data;
                        if (message.command === 'speak') {
                            textElement.value = message.text;
                            speakText(message.text);
                        }
                    });
                }());
            </script>
        </body>
        </html>
    `;
}